package sistemadearquivos;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author denilson
 */
public class TelaInicio extends javax.swing.JFrame {
    DefaultTableModel tArquivos = new DefaultTableModel(null, new String []{"Arquivo", "Indíce","N° de blocos"} );
    DefaultTableModel tDisco = new DefaultTableModel(null, new String []{"Posicao", "Nome","Indice"} );
    JTable tbArquivo = new JTable(tArquivos);
    JTable tbDisco = new JTable(tDisco);
    /**
     * Creates new form TelaInicio
     */
    public TelaInicio() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtDisco = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtArquivo = new javax.swing.JTable();
        jbMostrar = new javax.swing.JButton();
        jbIndexar = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jtfArquivo = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Sistema de Arquivos");

        jtDisco.setModel(tDisco);
        jScrollPane1.setViewportView(jtDisco);

        jtArquivo.setModel(tArquivos);
        jScrollPane2.setViewportView(jtArquivo);

        jbMostrar.setText("Mostrar");
        jbMostrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbMostrarActionPerformed(evt);
            }
        });

        jbIndexar.setText("Indexar");
        jbIndexar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbIndexarActionPerformed(evt);
            }
        });

        jButton1.setText("Buscar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jbIndexar)
                        .addGap(229, 229, 229)
                        .addComponent(jbMostrar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 322, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jtfArquivo)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                .addComponent(jtfArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbMostrar)
                    .addComponent(jbIndexar)
                    .addComponent(jButton1))
                .addGap(39, 39, 39))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbMostrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbMostrarActionPerformed
        try {
            gtArquivo();            
            gtDisco();
        } catch (Exception ex) {
            Logger.getLogger(TelaInicio.class.getName()).log(Level.SEVERE, null, ex);
        }
       
    }//GEN-LAST:event_jbMostrarActionPerformed

    private void jbIndexarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbIndexarActionPerformed
        try {
            // TODO add your handling code here:
            indexarArquivos();
        } catch (Exception ex) {
            Logger.getLogger(TelaInicio.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jbIndexarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        String nome = jtfArquivo.getText();
        Arquivo arquivo = new Arquivo();
        ArrayList<Arquivo> arquivos = new ArrayList();
        try {
            arquivos = arquivo.consultaArquivoDisco(nome);
        } catch (Exception ex) {
            Logger.getLogger(TelaInicio.class.getName()).log(Level.SEVERE, null, ex);
        }
        String saida = "";
        for(int i=0; i<arquivos.size();i++){
            
            saida += "\n"+arquivos.get(i).getNome()+" - posicao: "+arquivos.get(i).getPosicao()+" - com o dado: "+arquivos.get(i).getNome().substring(i,i+1);
            
        }
        JOptionPane.showMessageDialog(null, "O arquivo selecionado foi: "+nome+""+saida);
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaInicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaInicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaInicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaInicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaInicio().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbIndexar;
    private javax.swing.JButton jbMostrar;
    private javax.swing.JTable jtArquivo;
    private javax.swing.JTable jtDisco;
    private javax.swing.JTextField jtfArquivo;
    // End of variables declaration//GEN-END:variables
    public void gtArquivo() throws Exception{
        Arquivo arquivo = new Arquivo();
        ArrayList<Arquivo> listaArquivo = arquivo.consultarArquivo();
        String[] linha = new String[]{null,null,null};
        tArquivos.setRowCount(0);
        for(int i=0;i < listaArquivo.size() ;i++){
        tArquivos.addRow(linha);
        tArquivos.setValueAt(listaArquivo.get(i).getNome(), i, 0);
        tArquivos.setValueAt(listaArquivo.get(i).getInicio(), i, 1);
        tArquivos.setValueAt(listaArquivo.get(i).getBlocos(), i, 2);
        }
    }
    public void gtDisco() throws Exception{
        Arquivo arquivo = new Arquivo();
        ArrayList<Arquivo> listaArquivo = arquivo.consultarDisco();
        String[] linha = new String[]{null,null,null};
        tDisco.setRowCount(0);
        for(int i=0;i < listaArquivo.size() ;i++){
        tDisco.addRow(linha);
        tDisco.setValueAt(listaArquivo.get(i).getPosicao(), i, 0);
        tDisco.setValueAt(listaArquivo.get(i).getNome(), i, 1);
        tDisco.setValueAt(listaArquivo.get(i).getsIndice(), i, 2);
        }
    }
    public void indexarArquivos() throws Exception{
        Arquivo arquivo = new Arquivo();
        ArrayList<Arquivo> listaArquivo = arquivo.consultarArquivo();
        Arquivo aux;
        int auxindice = 1;
        int auxposicao = 1;
        for(int i=0; i<listaArquivo.size();i++){
            aux = new Arquivo();
            aux = listaArquivo.get(i);
            if(i != 0 && !listaArquivo.get(i).getNome().equals(listaArquivo.get(i-1).getNome())){
                auxindice++;
            }
            aux.setIndice(auxindice);
            for(int j=0; j < listaArquivo.get(i).getBlocos();j++){
                while(aux.verificaPosicao(auxposicao)){
                    auxposicao++;
                }
                aux.setDados(listaArquivo.get(i).getNome().substring(j, j+1));
                aux.setPosicao(auxposicao);
                aux.gravarDisco();
            }
        }
    }

}
